import React, { useEffect } from 'react';
import { observer } from 'mobx-react';
import { useDrawStores } from './store';
import { useLocation } from 'react-router-dom';
import { appWindow } from '@tauri-apps/api/window';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import s from './index.module.less';
import ReadDraw from './components/ReadDraw';
import WriteDraw from './components/WriteDraw';
import 'tldraw/tldraw.css';

const ProjectDraw = () => {
    const store = useDrawStores();

    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const projectId = urlParams.get("projectId") ?? "";
    const drawId = urlParams.get("drawId") ?? "";
    const inEditStr = urlParams.get("inEdit") ?? "false";

    useEffect(() => {
        store.projectId = projectId;
        store.drawId = drawId;
        store.loadProjectAndUser();
        store.loadDraw();
        appWindow.setAlwaysOnTop(true);
        setTimeout(() => {
            appWindow.setAlwaysOnTop(false);
        }, 500);
        store.inEdit = inEditStr.toLocaleLowerCase() == "true";
    }, []);

    useEffect(() => {
        appWindow.setClosable(!store.inEdit);
    }, [store.inEdit]);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.WatchChangeNotice != undefined) {
                if (notice.ClientNotice.WatchChangeNotice.targetId == store.drawId && !store.inEdit) {
                    store.loadDraw();
                }
            } else if (notice.EntryNotice?.UpdateEntryNotice != undefined) {
                if (notice.EntryNotice.UpdateEntryNotice.entry_id == store.drawId && !store.inEdit) {
                    store.loadDraw();
                }
            } else if (notice.ProjectNotice?.UpdateProjectNotice != undefined && notice.ProjectNotice.UpdateProjectNotice.project_id == store.projectId) {
                store.loadProjectAndUser();
            } else if (notice.ProjectNotice?.UpdateMemberNotice != undefined && notice.ProjectNotice.UpdateMemberNotice.project_id == store.projectId && notice.ProjectNotice.UpdateMemberNotice.member_user_id == store.myUserId) {
                store.loadProjectAndUser();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <>
            {store.project != null && store.draw != null && (
                <div className={s.draw_wrap}>
                    {store.inEdit && <WriteDraw />}
                    {!store.inEdit && <ReadDraw />}
                </div>
            )}
        </>
    );
};

export default observer(ProjectDraw);
